<?php

namespace App\Models;


use App\Traits\InsertOnDuplicateKey;
use Illuminate\Database\Eloquent\Model;

class ZPituitaryVisitRecords extends Model
{
    use InsertOnDuplicateKey;

    protected $table = 'z_pituitary_visit_records';

    protected $guarded = [];

    public $primaryKey = 'id';


    /**
     *  获取最新就诊患者
     * @param $date1
     * @param $date2
     * @return array
     */
    public static function getVisitList($date1, $date2)
    {
        return self::query()->from('z_pituitary_visit_records as r')
            ->selectRaw('r.user_id')
            ->where('r.updated_at', ">=", $date1)
            ->where('r.updated_at', '<=', $date2)
            ->where('r.visit_id', '>', 0)
            ->where('r.type', '=', 0)
            ->groupBy('user_id')
            ->get()->toArray();
    }

    /**
     *  获取用户就诊信息
     * @param $limit
     * @param $id
     * @param int $userId
     * @return array
     */
    public static function getUserVisitRecord($limit, $id, $userId = 0)
    {
        if (empty($userId)) {
            return [];
        }

        return self::query()->from('z_pituitary_visit_records as zuvh')
            ->selectRaw("zuvh.id,zuvh.user_id,zuvh.hosp_id,zuvh.dept_id")
            ->where('zuvh.user_id', $userId)
            ->where('zuvh.id', '>', $id)
            ->where('zuvh.visit_id', '>', 0)
            ->where('zuvh.type', '=', 0)
            ->orderBy('zuvh.id')
            ->groupBy(['zuvh.user_id', 'zuvh.hosp_id'])
            ->limit($limit)
            ->get()
            ->toArray();
    }

    /**
     * 获取最新就诊日期/第一次就诊信息
     * @param $userId
     * @param string $order
     * @return mixed
     */
    public static function getPatientInfoByUserId($userId, $order = 'desc')
    {
        $info = self::query()->from('z_pituitary_visit_records as r')
            ->leftJoin('z_pituitary_visit_level as vh', 'r.visit_id', '=', 'vh.id')
            ->where('r.user_id', $userId)
            ->where('r.visit_id', '>', 0)
            ->where('r.type', 0)
            ->orderBy('r.visit_at', $order)
            ->select(['vh.visit_level', 'r.visit_at'])
            ->first();

        return $info;
    }


}